package com.itheima.immediate;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * 客户端发送消息，客户端随时可能收到消息；它承担发和收
 * 发已经有主线程，在不停的发；所以收需要子线程
 */
public class Clien1 {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("127.0.0.1",6666);
        //创建一个独立的线程，专门负责这个客户端读消息
        new MyThread(socket).start();


        // 获得输出流
        OutputStream outputStream = socket.getOutputStream();
        PrintStream printStream = new PrintStream(outputStream);

        // 输出
        Scanner sc = new Scanner(System.in);
        while (true) {
            System.out.println("请说:");
            String msg = sc.nextLine();
            printStream.println(msg);
            printStream.flush();
        }
    }
}

class MyThread extends Thread{
    private Socket socket;
    public MyThread(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

            // 读
            String msg;
            while ((msg = reader.readLine())!=null) {
                System.out.println(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
